/**
 * Copyright (C) T-Systems International, 2013-2014
 *
 * The copyright of the computer program herein is the property of
 * T-Systems International. The program may be used and/or copied
 * only with the written permission of T-Systems International or in
 * accordance with the terms and conditions stipulated in the
 * agreement/contract under which the program has been supplied.
 *
 * $Author$
 * $Date$
 * $Rev$
 */
package com.tsystems.migdb.batch.validator;

import com.tsystems.migdb.batch.utils.MigdbToStringBuilder;
import lombok.AllArgsConstructor;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang.Validate;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.ValidationException;
import javax.validation.Validator;
import javax.validation.groups.Default;
import java.util.Set;

@Log4j2
@AllArgsConstructor
public class FieldValidator {

    private ValidationMessageGenerator validationMessageGenerator;

    public void validate(Object validatedObject) throws ValidationException {
        Validator validator = Validation.buildDefaultValidatorFactory().getValidator();
        log.info("Start validating object: \n" + MigdbToStringBuilder.toString(validatedObject));
        Set<ConstraintViolation<Object>> errors = validator.validate(validatedObject, Default.class);
        if (!errors.isEmpty()) {
            String validation = validationMessageGenerator.generateMessage(errors);
            //log.error(validation);
            throw new ValidationException(validation);
        }
        log.info("Validation success for: \n" + MigdbToStringBuilder.toString(validatedObject));
    }
}
